package org.kisekiproject.resources {
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.media.Sound;

	/**
	 * @author mikael
	 */
	public class ResourceLoader extends EventDispatcher {

		private var _bulkLoader:BulkLoader;
		private var _resourceUrls:Array;
		private var _preventCache:Boolean;

		/**
		 * Constructor.
		 */
		public function ResourceLoader() {
			_resourceUrls=new Array();
		}

		/**
		 * Add a resource to be loaded.
		 */
		public function addResource(url:String):void {
			if (_resourceUrls.indexOf(url)<0)
				_resourceUrls.push(url);
		}

		/**
		 * Prevent cache.
		 */
		public function set preventCache(value:Boolean):void {
			_preventCache=value;
		}
		
		/**
		 * Start loading.
		 */
		public function load():void {
			_bulkLoader=new BulkLoader("loader");

			for each (var url:String in _resourceUrls) {
				var useUrl:String=url;

				if (_preventCache)
					useUrl+="?preventcache="+Math.round(Math.random()*1000000000);

				trace("will load: "+url);
				_bulkLoader.add(useUrl,{id: url});
			}

			_bulkLoader.addEventListener(BulkLoader.COMPLETE,onBulkLoaderComplete);
			_bulkLoader.addEventListener(BulkLoader.ERROR,onBulkLoaderError);

			trace("--- loading resources ---");
			_bulkLoader.start();
		}

		/**
		 * Bulk loader error.
		 */
		protected function onBulkLoaderError(event:ErrorEvent):void {
			trace("bulk loader error...");
			_bulkLoader.clear();
			_bulkLoader=null;

			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,event.text));
		}

		/**
		 * Bulk loader complete.
		 */
		protected function onBulkLoaderComplete(event:Event):void {
			trace("bulk loader complete!!!!");
			dispatchEvent(new Event(Event.COMPLETE));
		}

		/**
		 * Get bitmap data.
		 */
		public function getBitmapData(url:String):BitmapData {
			return _bulkLoader.getBitmapData(url);
		}

		/**
		 * Get display object resource.
		 */
		public function getMovieClip(url:String):DisplayObject {
			return _bulkLoader.getMovieClip(url);
		}

		/**
		 * Get bitmap resource.
		 */
		public function getBitmap(url:String):Bitmap {
			return _bulkLoader.getBitmap(url);
		}

		/**
		 * Get sound resource.
		 */
		public function getSound(url:String):Sound {
			return _bulkLoader.getSound(url);
		}
	}
}
